<?php


namespace mail;


use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;

class smtp
{

    protected $username;
    protected $password;
    protected $server;
    protected $port;


    public function __construct($options)
    {
        $this->username=$options['username'];
        $this->password=$options['password'];
        $this->server=$options['server'];
        $this->port=$options['port'];
    }
    /**
     * @param $to
     * @param string $subject
     * @param string $body
     * @return array
     * @throws Exception
     * @describe:发送邮件
     */
    public  function send($to,$subject,$body='',$from_name=''){
        //判断openssl是否开启
        $openssl_funcs = get_extension_funcs('openssl');
        if(!$openssl_funcs){
            return ['code'=>0 , 'msg'=>'请先开启openssl扩展'];
        }
        $mail = new PHPMailer(true);
        $mail->CharSet = 'UTF-8';
        $config=sysconfig("smtp");
        // 服务器设置
        //$mail->SMTPDebug = 0; //开启Debug
        $mail->isSMTP(); // 使用SMTP
        $mail->Host = $this->server; // SMTP 服务器
        $mail->Port = $this->port; // SMTP服务器的端口号
        $mail->Username = $this->username;
        $mail->Password = $this->password;
        $mail->SMTPAuth = true; // 开启SMTP验证
        $mail->SMTPAutoTLS = false;
        switch ($mail->Port) {
            case 465:
                $mail->SMTPSecure = 'ssl';
                break;
            case 587:
                $mail->SMTPSecure = 'tls';
                break;
            default:
                # code...
                break;
        }
        if ($body == '') {
            $body = $subject;
        }
        if ($from_name == '') {
            $from_name = sysconfig('site.site_name');
        }
        $mail->SetFrom($config['username'], $from_name);
        $mail->Subject = $subject;
        $mail->MsgHTML($body);
        $mail->AddAddress($to, $from_name);
        try {
            $mail->Send();
            return ['code'=>1,'msg'=>'发送成功'];
        }catch (\Exception $e){
            return ['code'=>0,'msg'=>$e->getMessage()];
        }
    }

}